<template>
	<view>
		<!-- 收银台 -->
		<view class="edgeInsetTop"></view>
		<view class="wanl-pay">
			<view class="price-box">
				<text class="text-df">{{order_no}}</text>
				<text class="wanl-pip text-price margin-top-sm">{{price}}</text>
			</view>
			<view class="list-box">
				<view class="item" v-for="(item, index) in payList" :key="index">
					<text :class="'wlIcon-'+ item.type +'-pay'"></text>
					<view class="action">
						<text class="title wanl-pip">{{item.name}}</text>
						<!-- <view v-if="item.type == 'balance'">
							<text v-if="isbalance">可用余额 ￥{{user.money}}</text>
							<text v-else>余额不足，可用余额 ￥{{user.money}}</text>
						</view>
						<view v-else>{{item.describe}}</view> -->
						<view>{{item.describe}}</view>
					</view>
					<view class="radio text-xxl" v-if="item.state" @tap="onSelect(index)">
						<text v-if="item.select" class="wlIcon-xuanze-danxuan wanl-orange"></text>
						<text v-else class="wlIcon-xuanze wanl-gray-light"></text>
					</view>
					<view class="radio text-xxl" v-else>
						<text class="wlIcon-xuanze-danxuan wanl-gray-light"></text>
					</view>
				</view>
			</view>
			<view v-if="disabled">
				<button class="mix-btn wanl-bg-redorange"> <text
						class="wlIcon-jiazai wlIconfont-spin margin-right-xs"></text>正在支付中... </button>
			</view>
			<view v-else>
				<button v-if="payNum == 1" class="mix-btn wanl-bg-redorange" @tap="confirm()"> 确认支付 </button>
				<button v-else class="mix-btn wanl-bg-redorange" @tap="confirm()"> 合并支付 </button>
			</view>
			<view class="footer text-center">
				<view class="text-sm" v-if="order_pay_no">{{order_type === 'groups' ? '拼团':''}}交易号：{{order_pay_no}}
				</view>
				<!-- <view> © 万联支付</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				token: '',
				disabled: false,
				price: '0.00',
				freight_price:'0.00',
				isbalance: false,
				order_type: 'goods',
				order_no: '',
				order_pay_no: '',
				payNum: 1, // 支付方式 独立支付-合并支付
				payList: [],
				balanceToPay: '0.00', //当余额不等于0,且还是不够足额支付时,计算差额
				use_balance: 0, //组合支付 0单个支付  1组合支付
				isSelect:false,//用来控制支付方式--单选多选混合模式(false),单选互斥的模式(true)
				balanceDescribe:'',
				wechatDescribe:'',
			}
		},
		computed: {
			...mapState(['user'])
		},
		watch: {
			price(val, newval) {
				// console.log('监听price价格的变化执行不同的逻辑=====',val,newval);
				const availableBalance = parseFloat(this.$store.state.user.money);
				// 判断当前余额是否大于0
				if (availableBalance > 0) {
					// console.log('余额大于0', availableBalance);
					this.isbalance = true;
					// 订单额<=余额,余额足够支付
					if (val <= availableBalance) {
						this.balanceDescribe = `可用余额 ￥${availableBalance}`;
						if(this.freight_price > 0){
							// console.log('余额足够支付有运费');
							this.wechatDescribe = `快递费必须微信支付 ￥${this.freight_price}`
						}else{
							// console.log('余额足够支付没有运费');
							this.isSelect = true;//true单选互斥模式
						}
					}else{
						// console.log('不够足额支付,需要补差额');
						this.isSelect = false;//单选多选混合模式
						this.balanceDescribe = `余额不足,可用余额 ￥${availableBalance}`;
						this.balanceToPay = (val - availableBalance).toFixed(2); 
						if(this.freight_price > 0){
							// console.log('不够足额支付,需要补差额,有运费');
							this.wechatDescribe = `还需支付 ￥${this.balanceToPay}+快递费 ￥${this.freight_price}`
						}else{
							// console.log('不够足额支付,需要补差额,没运费');
							this.wechatDescribe = `还需支付 ￥${this.balanceToPay}`
						}
					}
				} else {
					// console.log('余额小于0');
					this.isbalance = false; //小于等于0禁用
					this.balanceDescribe = `余额不足,可用余额 ￥${availableBalance}`;
					if(this.freight_price > 0){
						this.wechatDescribe = `需支付 ￥${this.price}+快递费 ￥${this.freight_price}`
					}else{
						this.wechatDescribe = `需支付 ￥${this.price}`
					}
				}
				this.getPayment();
			}
		},
		async onLoad(option) {
			// console.log(JSON.parse(option.data))
			// console.log('页面进入后获取option======',option);
			await uni.request({
				url: '/wanlshop/pay/getBalance',
				method: 'POST',
				success: res => {
					this.$store.commit('user/setUserInfo', {
						money: res.data
					});
					// 获取支付列表
					this.getPayment();
				}
			});
			if (option.data) {
				var sum = 0,
					data = JSON.parse(option.data),
					order_ids = [];
					// console.log('data==正常下单跳转过来的==',data);
				if (data.length <= 1) {
					this.price = data[0].order_price;
					this.freight_price = data[0].freight_price;
					this.order_type = data[0].type;
					this.order_no = `${data[0].type == 'groups' ? '拼团':''}订单号：${data[0].order_no}`;
					this.order_pay_no = data[0].pay_no;
					this.order_id = data[0].order_id;
				} else {
					data.forEach(item => {
						sum = this.$wanlshop.bcadd(sum, item.price);
						order_ids.push(item.order_id);
					});
					this.price = sum;
					this.order_id = order_ids;
					this.payNum = data.length;
					this.order_no = '合并支付 ' + data.length + '个订单';
				}
				this.token = option.token;
			} else if (option.order_id) {
				// console.log('data==通过订单列表=去支付跳转过来的==',option);
				uni.showLoading({
					title: '结算中...'
				});
				await uni.request({
					url: '/wanlshop/pay/getPay',
					method: 'POST',
					data: {
						order_id: option.order_id,
						order_type: option.order_type
					},
					success: res => {
						// console.log('拿着订单号去请求数据返回的====',res);
						uni.hideLoading();
						this.token = res.data.token;
						this.price = res.data.order_price;
						this.freight_price = res.data.freight_price;
						this.order_type = res.data.order_type;
						this.order_no =`${res.data.order_type == 'groups' ? '拼团':''}订单号：${res.data.order_no}`;
						this.order_pay_no = res.data.pay_no;
						this.order_id = res.data.order_id;
					}
				});
			} else {
				console.log('非法访问');
			}
		},
		methods: {
			getPayment() {
				this.payList = [{
						name: '余额支付',
						describe: this.balanceDescribe,
						type: 'balance',
						method: 'balance',
						state: this.isbalance,
						select: this.$store.state.user.money > 0
					},
					{
						name: '微信支付',
						describe: this.wechatDescribe,
						type: 'wechat',
						method: 'miniapp',
						state: true,
						select: !this.isSelect
					}
				];
			},
			//确认支付
			confirm() {
				let data = null;
				let dataNum = [];
				if (this.disabled) {
					return;
				}
				this.payList.map((value, index, array) => {
					if (value.select) {
						data = value;
						dataNum.push(value);
					} else {
						return;
					}
				});
				if (dataNum.length > 1) {
					this.use_balance = 1;
				}
				// 判断支付是否存在
				if (!data) {
					uni.showModal({
						content: "请选择支付方式",
						showCancel: false
					});
					return;
				} else {
					this.disabled = true;
					// 获取小程序code
					uni.login({
						success: (e) => {
							this.wanlPay(data, e.code);
						},
						fail: (e) => {
							uni.showModal({
								content: "无法获取微信code,原因为: " + e.errMsg,
								showCancel: false
							})
						}
					})
				}

			},
			async wanlPay(data, code = null) {
				await uni.request({
					url: '/wanlshop/pay/payment',
					method: 'POST',
					data: {
						order_type: this.order_type,
						type: data.type,
						method: data.method,
						code: code,
						order_id: this.order_id,
						token: this.token,
						use_balance: this.use_balance
					},
					success: res => {
						if (this.use_balance > 1) {
							uni.requestPayment({
								appId: res.data.appId,
								nonceStr: res.data.nonceStr,
								package: res.data.package,
								paySign: res.data.paySign,
								signType: res.data.signType,
								timeStamp: res.data.timeStamp,
								success: (e) => {
									// console.log(e);
									this.$store.commit('user/setUserInfo', {
										money: this.$wanlshop.bcsub(this.$store.state.user.money,
											this.price)
									});
									this.paySuccess();
								},
								fail: (e) => {
									uni.showModal({
										content: "支付失败,原因为: " + e.errMsg,
										showCancel: false
									})
								}
							})

						} else {
							switch (data.type) {
								case 'balance':
									this.$store.commit('user/setUserInfo', {
										money: this.$wanlshop.bcsub(this.$store.state.user.money,
											this.price)
									});
									this.paySuccess();
									break;
								case 'wechat':
									if (data.method == 'miniapp') {
										uni.requestPayment({
											appId: res.data.appId,
											nonceStr: res.data.nonceStr,
											package: res.data.package,
											paySign: res.data.paySign,
											signType: res.data.signType,
											timeStamp: res.data.timeStamp,
											success: (e) => {
												this.paySuccess();
											},
											fail: (e) => {
												uni.showModal({
													content: "支付失败,原因为: " + e.errMsg,
													showCancel: false
												})
											}
										})
									}
									break;
							}
						}
					}
				});
			},
			onSelect(key) {
				if(this.isSelect){
					//单选互斥模式
					this.payList.map((value, index, array) => {
						if (index == key) {
							value.select = !value.select;
						}else{
							value.select = false;
						}
					});
				}else{
					//混合模式支付
				}
				
			},
			// 支付成功
			paySuccess() {
				this.disabled = false;
				if (this.order_type === 'goods') {
					this.$store.commit('statistics/order', {
						pay: this.$wanlshop.bcsub(this.$store.state.statistics.order.pay, this.payNum),
						delive: this.$wanlshop.bcadd(this.$store.state.statistics.order.delive, this.payNum)
					});
				}
				this.$wanlshop.to(`/pages/page/success?type=pay&order_type=${this.order_type ? this.order_type:'goods'}`);
			}
		}
	}
</script>

<style>
	page {
		background-color: white;
	}

	radio-group {
		display: block;
	}
</style>